import * as fs from "fs";
import * as path from "path";
import axios from "axios";

// ====== 配置区 ======
const DEPENDENCIES_DIR = path.resolve(__dirname, "../下载的依赖包");
const NEXUS_UPLOAD_URL = "http://xxxxx/repository/npm-hosted/";
const NEXUS_USERNAME = "username";
const NEXUS_PASSWORD = "password";
// ====================

// 递归遍历文件夹，获取所有文件路径
function getAllFiles(dir: string, fileList: string[] = []): string[] {
  const files = fs.readdirSync(dir);
  files.forEach((file) => {
    const filePath = path.join(dir, file);
    const stat = fs.statSync(filePath);
    if (stat.isDirectory()) {
      getAllFiles(filePath, fileList);
    } else {
      fileList.push(filePath);
    }
  });
  return fileList;
}

// 上传单个文件到Nexus
async function uploadFileToNexus(filePath: string) {
  const fileName = path.basename(filePath);
  const fileStream = fs.createReadStream(filePath);

  try {
    const response = await axios.post(NEXUS_UPLOAD_URL, fileStream, {
      headers: {
        "Content-Type": "application/octet-stream",
        "Content-Disposition": `attachment; filename="${fileName}"`,
      },
      auth: {
        username: NEXUS_USERNAME,
        password: NEXUS_PASSWORD,
      },
      maxContentLength: Infinity,
      maxBodyLength: Infinity,
    });
    console.log(`上传成功: ${fileName}`, response.status);
  } catch (error: any) {
    console.error(
      `上传失败: ${fileName}`,
      error.response?.status,
      error.message
    );
  }
}

// 主流程
async function main() {
  const files = getAllFiles(DEPENDENCIES_DIR);
  for (const file of files) {
    await uploadFileToNexus(file);
  }
}

main().catch(console.error);
